import { doLogin } from "@/api/auth";
import { defineStore } from "pinia";
import { ref } from "vue";


export interface AccessControlStore {
    accessCode: string;
    token: string;
    accessCodeErrorMsgs: string;

    updateToken: (_: string) => void;
    updateCode: (_: string) => void;
    isAuthorized: () => boolean;
    login: () => Promise<string>;
    goToLogin: () => void;
}


export const useAuthStore = defineStore('auth', () => {
    const token = ref("");
    const accessCode = ref("");
    const accessCodeErrorMsgs = ref("");

    // 登录
    async function login() {
        const res: any = await doLogin(accessCode.value);
        console.log(res);

        const { code, data } = res;
        if (code === '0000') {
            console.log('登录成功');
            updateToken(data);
            accessCodeErrorMsgs.value = '';
        } 

        if (code === '0002') {
            accessCodeErrorMsgs.value = '验证码已过期,请获取最新验证码';
        }

        if (code === '0003') {
            accessCodeErrorMsgs.value = '验证码不存在,请确认最新验证码';
        }
        return data;
    }

    // 修改code
    function updateCode(code: string) {
        accessCode.value = code;
    }

    // 修改token
    function updateToken(value: string) {
        token.value = value;
    }

    // 是否授权
    function isAuthorized() {
        return token;
    }

    // 去登录
    function goToLogin() {
        updateCode("");
        updateToken("");
    }

    return {
        accessCodeErrorMsgs,
        accessCode,
        token,
        login,
        updateCode,
        updateToken,
        isAuthorized,
        goToLogin,
    };
});